#include "Keyboard.h"
#include <iostream>

using namespace std;

void cKeyboard::Init() {
	// Initialize the InputBuffer
	memset(mabInputBuffer, 0, kuiInputChanelSize);
	// Get the standard input handle
	mStdin = GetStdHandle(STD_INPUT_HANDLE);

	if (mStdin == INVALID_HANDLE_VALUE) {
		cerr << "Error: GetStdHandle" << endl;
		return;
	}

	// Save the current input mode, to be restored on exit
	if (!GetConsoleMode(mStdin, &mOldModeSaved)) {
		cerr << "Error: GetConsoleMode" << endl;
		return;
	}

	DWORD lNewMode = ENABLE_WINDOW_INPUT;
	if (!SetConsoleMode(mStdin, lNewMode)) {
		cerr << "Error: SetConsoleMode" << endl;
		return;
	}
	mbIsValid = true;
}

void cKeyboard::DeInit() {
	if (!SetConsoleMode(mStdin, mOldModeSaved)) {
		cerr << "Error: SetConsoleMode" << endl;
		return;
	}
	mbIsValid = false;
}

void cKeyboard::Update() {
	INPUT_RECORD laInBuff[kuiInputBufferSize];
	DWORD luiNumRead;

	// Check if there are events
	if (!PeekConsoleInput( mStdin, laInBuff, kuiInputBufferSize, &luiNumRead)) {
		cerr << "Error: PeekConsoleInput" << endl;
		return;
	}

	if (luiNumRead > 0) {
		// Read the events and clear the buffer
		if ( !ReadConsoleInput(mStdin, laInBuff, kuiInputBufferSize, &luiNumRead)) {
			cerr << "Error: ReadConsoleInput" << endl;
			return;
		}

		// Dispatch the events to the appropiate handler
		for (register unsigned luiIndex = 0; luiIndex < luiNumRead; luiIndex++) {
			// Keyboard input
			if (laInBuff[luiIndex].EventType == KEY_EVENT)
				KeyEventProc(laInBuff[luiIndex].Event.KeyEvent);
		}
	}
}

void cKeyboard::KeyEventProc(KEY_EVENT_RECORD lKey) {
	if (lKey.wVirtualKeyCode >= 0 && lKey.wVirtualKeyCode < kuiInputChanelSize)
		mabInputBuffer[ lKey.wVirtualKeyCode ] = (lKey.bKeyDown == TRUE);
}

float cKeyboard::Check(unsigned int luiEntry) {
	return (mabInputBuffer[luiEntry])? 1.0f: 0.0f;
}